﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FlowSequencer.Core.Sequencer.Helper
{
    public static class MathHelper
    {
        public static int Nwd(int a, int b)
        {
            int temp;
            while (b != 0)
            {
                temp = a % b;
                a = b;
                b = temp;
            }
            return a;
        }


        internal static int Nwd(List<int> periods)
        {
            int nwd = periods.Min();
            var divisros = GetDivisors(periods);
            divisros.Sort(new Comparison<int>(
                            (i1, i2) => i2.CompareTo(i1)
                    ));

            foreach (var divisor in divisros)
            {
                bool isNwd = true;
                foreach (var period in periods)
                {
                    if (period % divisor != 0)
                    {
                        isNwd = false;
                        break;
                    }
                }
                if(isNwd)
                    return divisor;
            }

            return 1;
        }

        private static List<int> GetDivisors(List<int> periods)
        {
            int min = periods.Min();
            var divisros = new List<List<int>>();
            for (int i = 0; i < periods.Count; i++)
            {
                divisros.Add(new List<int>());
                for (int j = 1; j <= min; j++)
                {
                    if(periods[i] % j == 0)
                        divisros[i].Add(j);
                }
            }

            List<int> result = divisros[0];
            foreach (var divCollection in divisros)
            {
                result.Union(divCollection);
            }
            return result;
        }
    }
}
